var util = require('../../utils/util.js'); //导入实现时间获取
var app = getApp();
const db = wx.cloud.database({
  throwOnNotFound: false
})
const _ = db.command
Page({
  data: {
    id: 0,
    detail: [],
    price2: 0,
    re: false,
    nowNum: 0,
    likenum: 0,
    type: "",
    content: "",
    time: "",
    nowMoney: 0,
  },
  onLoad: function (options) {
    let id = options.id;
    console.log("id:is", id)
    this.setData({
      id: id
    });
    this.getDetail();

    //微信获取授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              wx.cloud.callFunction({ //调用云函数获取openid
                name: "getOpenId",
                complete: res => {
                  db.collection("userInfo").where({
                    _openid: res.result.openid //进行筛选
                  }).get({
                    success: res => {
                      if (res.data.length === 1) {
                        that.setData({
                          re: true
                        })
                        wx.navigateTo({
                          url: '/pages/home/home',
                        })
                      } else {
                        that.setData({
                          re: false
                        })
                      }
                    }
                  })
                }
              });
            }
          });
        } else {
          wx.redirectTo({
            url: '../mine/login'
          });
        }
      }
    })


    //判断用户是否注册，返回re值true/false
    wx.cloud.callFunction({ //调用云函数获取openid
      name: "getOpenId",
      complete: res => {
        db.collection("userInfo").where({
          _openid: res.result.openid //进行筛选
        }).get({
          success: res => {
            console.log("查找用户注册信息成功", res.data)
            if (res.data.length === 1) {
              this.setData({
                  re: true
                }),
                console.log("用户已注册", this.data.re)
            } else {
              this.setData({
                  re: false
                }),
                console.log("用户未注册", this.data.re)

            }
          },
          fail: res => {
            console.log("查找用户注册信息失败", res)
          }
        })
      }
    });

  },

  //访问网络,请求数据  
  getDetail() {
    var that = this;
    let id = this.data.id;
    if (!id) {
      wx.showToast({
        icon: "none",
        title: '参数错误',
        duration: 3000,
      })
      return;
    }
    wx.showLoading({
      title: '数据加载中',
      mask: true,
    })
    wx.cloud.callFunction({
      name: 'queryData',
      data: {
        id: this.data.id
      },
      success: res => {
        console.log('[云函数] [queryWelfareDetail 调用成功] : ', res.result)
        if (res.result) {
          that.setData({
            detail: res.result.data,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.result.msg,
            duration: 2000,
          })
        }

      },
      fail: err => {
        console.error('[云函数] [queryData] 调用失败', err)
        wx.showToast({
          icon: "none",
          title: "获取数据失败",
          duration: 2000,
        })
      },
      complete: () => {
        wx.hideLoading();
      }
    })

  },

  toDonation: function () {
    let id = this.data.id;
    let re = this.data.re;
    let price2 = this.data.price2;
    let donated = this.data.donated;
    let detail = this.data.detail;
    let likenum = this.data.likenum;
    if (re == false) {
      console.log("用户未注册", this.data.re)
      this.setData({
          re: false
        }),
        wx.showModal({
          title: '提示',
          content: '请先注册成为志愿者！',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定'),
                wx.navigateTo({
                  url: '../register/newuser',
                })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

    } else {

      //判断用户时间货币是否足够
      db.collection("WelfareList").doc(id).field({
        evenum: true,
        name: true
      }).get({
        success: (res) => {
          console.log(res)

          this.setData({
            price2: res.data.evenum,
            content: res.data.name,
            type: "公益捐赠",
            time: util.formatTime(new Date())
          })

          console.log("price2为：", this.data.price2)

          wx.cloud.callFunction({
            name: "getOpenId",
            complete: res => {
              db.collection("userInfo").where({
                _openid: res.result.openid
              }).get({
                success: res => {
                  console.log("该用户的_id为：", res)
                  console.log("该用户的时间货币为：", res.data[0].timecurrency)
                  this.setData({
                    nowMoney: res.data[0].timecurrency - this.data.price2
                  })

                  if (res.data[0].timecurrency < this.data.price2) {
                    wx.showToast({
                      title: '时间货币不足',
                    })

                    console.log("时间货币不足")

                  } else {
                    //时间货币足够的情况下,判断已捐赠数donated是否小于所需捐赠数maxnum


                    db.collection("WelfareList").doc(id).field({
                      maxnum: true,
                      donated: true,
                      likenum: true
                    }).get({
                      success: (res) => {
                        console.log(res)
                        this.setData({
                          donated: res.data.donated,
                          likenum: res.data.likenum
                        })
                        if (res.data.donated < res.data.maxnum) {
                          console.log("donated<maxnum，允许捐赠", res.data.donated)

                          console.log("弹出捐赠确认框")
                          wx.showModal({
                            title: '捐赠确认',
                            content: '您确认捐赠吗',
                            success: (res) => {
                              if (res.confirm) {
                                console.log('用户点击确定')
                                wx.showToast({
                                    title: '捐赠成功！',
                                    icon: '', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                                    duration: 1200, //停留时间
                                  }),
                                  //WelfareList数据库更新donated+price2
                                  db.collection('WelfareList').doc(id).update({
                                    data: {
                                      donated: _.inc(+this.data.price2)
                                    },
                                    success: (res) => {

                                      console.log("捐赠成功，donated+price2", res)
                                      //更新数组,使得页面donated更新
                                      this.getDetail();

                                      //查找用户的_id，通过id更新待爱心数据,userInfo的auditexchange+1,时间货币相应的减少
                                      wx.cloud.callFunction({ //调用云函数获取openid
                                        name: "getOpenId",
                                        complete: res => {
                                          db.collection("userInfo").where({
                                            _openid: res.result.openid //进行筛选
                                          }).get({

                                            success: res => {
                                              console.log("该用户的_id为：", res.data[0]._id)
                                              db.collection('userInfo').doc(res.data[0]._id).update({
                                                data: {
                                                  gotlike: _.inc(+this.data.likenum),
                                                  timecurrency: _.inc(-this.data.price2)
                                                }
                                              })
                                              console.log("更新成功，爱心数增加,时间货币减少")

                                              //增加该用户明细记录
                                              db.collection("history").add({
                                                data: {
                                                  content: this.data.content,
                                                  price: this.data.price2,
                                                  type: this.data.type,
                                                  time: this.data.time,
                                                  nowMoney: this.data.nowMoney
                                                },
                                                success: res => {
                                                  console.log("明细记录添加成功", res)
                                                }

                                              })

                                            },
                                            fail: res => {
                                              console.log("获取用户_id信息失败", res)
                                            }
                                          })
                                        }
                                      });

                                    },
                                    fail: function (res) {
                                      console.log("更新num失败", res)

                                    }
                                  })
                              } else if (res.cancel) {
                                console.log('用户点击取消')
                              }
                            }
                          })

                        } else {
                          wx.showToast({
                            title: '抱歉捐赠已结束',
                          })
                        }
                      }
                    })


                  }
                },
                fail: res => {
                  console.log("获取用户_id信息失败", res)
                }
              })
            }
          });


        }
      })

    }
  }


})